<?php
using("Db_Common_PreparedStatement");

/**
 * PDO Prepared Statement
 * 
 * @author Patrick J. Mizer
 * @package junction.db.pdo
 */
class Db_Pdo_PreparedStatement implements Db_Common_PreparedStatement
{
	/**
	 * PDO Prepared Statement
	 * 
	 * @var PDOStatement
	 */
	private $_statement;
	
	/**
	 * Sql query
	 * 
	 * @var string
	 */
	private $_query;
		
	/**
	 * Prepared statement constructor.
	 * 
	 * @param string SQL query.
	 */
	public function __construct($stmt, $sql)
	{
		$this->_statement 	= $stmt;
		$this->_query		= $sql;
	}
	
	/**
	 * Execute the prepared SELECT statement.
	 * 
	 * @throws Db_Common_SqlException
	 * @param array SQL parameters.
	 * @return Db_Pdo_ResultSet
	 */
	public function executeSelect(array $params = null)
	{
	 	if($this->_statement == false){
	 		throw new Db_Common_SqlException('Invalid SQL', $this->_query);
	 	}
	 	
	 	if(strpos(trim(strtolower($this->_query)), 'select') !== 0){
	 		throw new Db_Common_SqlException('Only SELECT SQL may be sent to the executeSelect() method!', $this->statement->queryString);
	 	}
	 	
	 	try{
	 		$this->affectedRows = $this->_statement->execute($params);
	 	}catch(PdoSqlException $e){
	 		throw new Db_Common_SqlException($e->getMessage, $this->statement->queryString);
	 	}
	 	
	 	return new Db_Pdo_ResultSet($this->_statement, $this->statement->queryString);
	}

	/**
	 * Execute the prepared non SELECT statement.
	 * 
	 * @throws Db_Common_SqlException
	 * @param array SQL parameters.
	 * @return boolean
	 */	
	public function executeSave(array $params = null)
	{
	 	if($this->_statement == false){
	 		throw new Db_Common_SqlException('Invalid SQL', $this->_query);
	 	}
	 			
		if(strpos(trim(strtolower($this->_query)), 'select') === 0){
	 		throw new Db_Common_SqlException('SELECT SQL may not be sent to the executeSave() method!', $this->statement->queryString);
	 	}
	 	
	 	try{
	 		$this->affectedRows = $this->_statement->execute($params);
	 	}catch(PdoSqlException $e){
	 		throw new Db_Common_SqlException($e->getMessage, $this->statement->queryString);
	 	}
	 	
	 	return true;	 	
	}
	
	/**
	 * Gets the number of rows affected by the query.
	 * 
	 * @return int affect rows
	 */
	public function affectedRows()
	{
		return $this->_statement->rowCount();
	}
	
	public function lastInsertId()
	{
		
	}
	
	/**
	 * Returns the prepared statement's query
	 * 
	 * @return string 
	 */
	public function getQuery()
	{
		return $this->_query;
	}
	

}
?>